package controller.login
{
	import controller.SocketManager;
	import controller.BaseController;	
	import controller.lobby.LobbyController;
	import mx.controls.Alert;
	import mx.core.FlexGlobals;
	import controller.events.SocketEvent;
	
	public class LoginController extends BaseController
	{
		// static instance 2012.4.8 23:50
		public static var instance:LoginController = null;
		
		public var userId:String;
		public function LoginController()
		{
			super();
			if ( instance != null )
				throw new Error( "Only one Singleton instance should be instantiated" ); 
		}
		static public function get Instance():LoginController
		{
			if ( instance == null )
				instance = new LoginController();
			return instance;
		}
		public function Login():void
		{
			if (FlexGlobals.topLevelApplication.txt_username.text.length<1) {
				Alert.show('input username');
				return;
			}
			if (FlexGlobals.topLevelApplication.txt_password.text.length<1) {
				Alert.show('input password');
				return;
			}
			initEvents();
			SocketManager.Instance.send(this.CreateOutMessage(BaseController.PLAYER,"LOGIN_SIGN_IN",FlexGlobals.topLevelApplication.txt_username.text+"~"+FlexGlobals.topLevelApplication.txt_password.text));
//			SocketManager.Instance.send("1~1~LOGIN_SIGN_IN~"+FlexGlobals.topLevelApplication.txt_username.text+"~"+FlexGlobals.topLevelApplication.txt_password.text);
		}
		
		private function initEvents():void{
			SocketManager.Instance.addEventListener(SocketEvent.LOGIN_SUCCESS,LoginHandler);
			SocketManager.Instance.addEventListener(SocketEvent.LOGIN_USER_ALREADY_ONLINE,LoginHandler);
			SocketManager.Instance.addEventListener(SocketEvent.LOGIN_IP_CONFLICT,LoginHandler);
			SocketManager.Instance.addEventListener(SocketEvent.LOGIN_ERROR_USERNAME_OR_PASSWORD,LoginHandler);
			
		}
		private function removeEvents():void{
			SocketManager.Instance.removeEventListener(SocketEvent.LOGIN_SUCCESS,LoginHandler);
			SocketManager.Instance.removeEventListener(SocketEvent.LOGIN_USER_ALREADY_ONLINE,LoginHandler);
			SocketManager.Instance.removeEventListener(SocketEvent.LOGIN_IP_CONFLICT,LoginHandler);
			SocketManager.Instance.removeEventListener(SocketEvent.LOGIN_ERROR_USERNAME_OR_PASSWORD,LoginHandler);
			
		}

		public function LoginHandler(event:SocketEvent):void
		{
			removeEvents();
			var results:Array=event.results;	
			trace("接收到派发消息："+event.type);
			switch(event.type)
			{
				case SocketEvent.LOGIN_ERROR_USERNAME_OR_PASSWORD:	
				{					
					mx.controls.Alert.show("用户名或密码错误\n");  
					break;
				}
				case SocketEvent.LOGIN_USER_ALREADY_ONLINE:
					Alert.show(" 玩家已经登陆，请换其他账号\n");  
					break;
				case SocketEvent.LOGIN_SUCCESS:
//					trace("LOGIN_SUCCESS");	
					this.userId=results[3];
				    LobbyController.Instance.initEvents();
					FlexGlobals.topLevelApplication.currentState = "GameLobby";
					break;
			}
			return;
		}
	}
}